package com.woniu.userservice.controller;


import com.woniu.userservice.entity.ResultBody;
import com.woniu.userservice.service.AccountService;
import com.woniu.userservice.service.UsersService;
import com.woniu.userservice.util.MD5_Encoding;
import com.woniu.userservice.util.RegexUtil;
import com.woniu.userservice.util.SDKTestSendTemplateSMS;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * @Auther: 李浪  <br/>
 * @Date: 2020/3/24:23:02  <br/>
 * @Description:登录注册
 */
@RestController
public class LoginController {

    @Resource
    private UsersService usersService;

    @Resource
    private AccountService accountService;

    /**
     * Description : TODO  验证码随机生成<br/>
     * ChangeLog : 1. 创建 (2020/3/26 10:22 [李浪]);
     *
     * @return null
     */
    @RequestMapping("/getValidateCode")
    public void getValidateCode(@RequestParam String account,HttpServletRequest request) {
        //验证数据合法性
        if (!RegexUtil.isMobile(account)) {
            return ;
        }
        //从以下数组中随机生成数字验证码
        Integer[] validateCodes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random random = new Random();
        String validateCode = "";
        //随机生成四位数字验证码
        for (int i = 0; i < 4; i++) {
            validateCode += random.nextInt(9);
        }
        //发送手机验证码
        SDKTestSendTemplateSMS.sendMessage(validateCode,account);
        System.out.println(validateCode);
        //将验证码放到seesion中
//        request.getSession().setAttribute("validateCode", validateCode);

    }

    /**
     * Description : TODO  密码登录方法<br/>
     * ChangeLog : 1. 创建 (2020/3/26 0:58 [李浪]);
     *
     * @return null
     */
    @PostMapping(value = "/login")
    public ResultBody login(String account, String pass) {
        //非空校验
        if (account == null || pass == null) {
            return ResultBody.error("登陆失败！");
        }
        //验证数据合法性
        if (!RegexUtil.isMobile(account)) {
            return ResultBody.error("请输入正确的手机号！");
        }
        if (!RegexUtil.isPassword(pass)) {
            return ResultBody.error("密码格式错误！");
        }
        //加密密码
        pass = MD5_Encoding.upperMD5(pass);
        //将账号密码与数据库进行对比
        return accountService.login(account, pass);
    }

    @RequestMapping("/register")
    public ResultBody register(@RequestParam String userName, @RequestParam String account, @RequestParam String pass, @RequestParam String validateCode) {
        //验证数据合法性
        if (!RegexUtil.isMobile(account)) {
            return ResultBody.error("请输入正确的手机号！");
        }
        if (!RegexUtil.isPassword(pass)) {
            return ResultBody.error("密码格式错误！");
        }
        //验证验证码

        //加密密码
        pass = MD5_Encoding.upperMD5(pass);
        //将账号密码与数据库进行对比
        return accountService.register(userName, account, pass);
    }

}
